/**
 * The TabPanel user-interface component class
 * @class syslib.ui.TabPanel
 * @author Gabriel Ricci
 */
syslib.ui.TabPanel = __class(syslib.ui.VisualTag, 
/** 
 * @lends syslib.ui.TabPanel
 */
{
	id : "", 
	contentBody : "", 
	tabs : "", 
	tabItens : [],
	tabCount : 0, 
	head : {}, 
	body : {}, 

	prepare : function(element){
		// STYLE
		syslib.loadStyleForComponent("tabs");

		// SETS
		this.id = (__valid(this.__attributes.id) ? this.__attributes.id : "tabpanel_"+Math.floor(Math.random() * 101));
		this.tabs = this.id + "_tabs_container";
		this.contentBody = this.id + "content_container";
		
		// RETURN
		return true;
	},

	execute : function(){
		// ATTRIBUTES
		var attributes = syslib.object.extend(this.__attributes, {
			"class" : "tabs-main-container"
		});

		// JSON STRUCTURE
		elemtJSON = ["div", attributes,
				["div", {"innerName" : "head", "class" : "tab-panel-top-container", "id" : this.tabs} ],
			["div", {"class" : "line"} ],
			["div", {"innerName" : "body", "class" : "tab-panel-main-container", "id" : this.contentBody} ]
		];

		// CREATE THE ELEMENT
		var tabPanel = this.createDOM(elemtJSON);
		delete elemtJSON;

		// INNERHTML UPDATE
		this.__refs.head.innerHTML 	= this.__innerHTML;
		
		// SETS
		this.head = this.__refs.head;
		this.body = this.__refs.body;

		// RETURN
		return tabPanel;
	},

	finalize : function(){},

	addTab : function(tabItem){
		if(typeof tabItem === 'object'){
			try{
				var container	 	= document.createElement("div");
				var count			= this.tabCount;

				container.style.display 	= "none";
				container.innerHTML 		= tabItem.__innerHTML;
				container.id				= "tabpanel_" + this.id + "_content_" + count;
				tabItem.container			= container;

				this.__refs.body.appendChild(container);
				this.tabItens[count] = tabItem;
				this.tabCount = count + 1;

				if(count == 0){this.selectTab(count);}
				return count;
			} catch(e){
				syslib.messages.error(e.message);
				return false;
			}
		}
	},

	selectTab : function(count){
		var tabitens = this.tabItens;
		for(var i in tabitens){
			if(isNaN(i)){continue;}  // PREVENT IE ERRORS
			var tabItem 	= tabitens[i];
			var attributes	= (__valid(tabItem.__attributes)) ? tabItem.__attributes : {};
			var contentElmt	= tabItem.container;

			if(!__valid(attributes) || !__valid(contentElmt)){
				syslib.messages.error("Invalid tab index: " + count);
				return false;
			}

			if(i == count){
				if(__valid(tabItem.__attributes.page)){
					syslib.element.update(contentElmt, '');
					new syslib.ajax.request(tabItem.__attributes.page, {
						destiny : contentElmt,
						store : false
					});
				}
				syslib.element.show(contentElmt);
				tabItem.__select();
			} else {
				syslib.element.hide(contentElmt);
				tabItem.__unselect();
			}
		}
	}
});